# coding:utf-8
import configparser
import os

import requests
import sys
from lxml import etree
import re


class Github:
    def __init__(self):
        self.login_url_get = 'https://github.com/login'
        self.login_url_post = 'https://github.com/session'
        self.url_desc = 'https://github.com/settings/emails'
        self.filename = 'ext/E12_github_login.html'
        self.post_data = {
            'commit': 'Sign in',
            'utf8': '✓',
            'authenticity_token': '',
            'login': '',
            'password': ''
        }
        _path = os.path.join(os.path.abspath('.'), '../')
        sys.path.append(_path)
        self.ei = __import__('Utils.C002_extract_info', fromlist=['C002_extract_info'])
        self.ua_file = {'pc': '{0}Utils/{1}'.format(_path, self.ei.ExtractInfo.ua_file['pc'])}

    def run(self):
        _user_agent = self.ei.ExtractInfo.get_useragent(file=self.ua_file)

        _s = requests.session()
        _response_get = _s.get(self.login_url_get, headers=_user_agent, verify=False)
        _html = etree.HTML(_response_get.content)

        _token = _html.xpath('//input[@name="authenticity_token"]/@value')[0]
        _user_pswd_cfg = os.environ['user_pswd']
        _cf = configparser.ConfigParser()
        _cf.read(_user_pswd_cfg)
        self.post_data['login'] = _cf.get('github', 'github_user')
        self.post_data['password'] = _cf.get('github', 'github_pswd')
        self.post_data['authenticity_token'] = _token

        _s.post(self.login_url_post, headers=_user_agent, data=self.post_data)
        _response_desc = _s.get(self.url_desc, headers=_user_agent)
        _html = _response_desc.content.decode()

        if re.findall(r'516960831@qq.com', _html):
            with open(self.filename, mode='w', encoding='utf-8')as f:
                f.write(_html)
        else:
            print('not found!')


def main():
    fh = Github()
    fh.run()


if __name__ == '__main__':
    main()
